package cn.ssm.service;

import cn.ssm.dao.AppCategoryDao;
import cn.ssm.entity.AppCategory;
import cn.ssm.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryService {
    @Autowired
    AppCategoryDao appCategoryDao;
    public CategoryVo getTree() {
        List<CategoryVo> tree=new ArrayList<>();
        List<AppCategory> categories = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory category : categories) {
            CategoryVo categoryVo=new CategoryVo();
            BeanUtils.copyProperties(category,categoryVo);
            tree.add(categoryVo);
        }

        CategoryVo categoryVo=new CategoryVo();
        for (CategoryVo vo : tree) {
            if(vo.getParentid()==null){
                categoryVo=findChild(vo,tree);
            }
        }
        return categoryVo;
    }


    private CategoryVo findChild(CategoryVo categoryVo,List<CategoryVo> treevo){
        categoryVo.setChildren(new ArrayList<>());
        for (CategoryVo vo : treevo) {
            if (categoryVo.getId()==vo.getParentid()) {
                categoryVo.getChildren().add(vo);
                findChild(vo,treevo);
            }
        }
        return categoryVo;
    }
}
